import { defineStore } from "pinia";
import type { reqCategoryListType } from "@/api/Attr";
import {
  requestCategoryList1,
  requestCategoryList2,
  requestCategoryList3,
} from "@/api/Attr";
import { ElMessage } from "element-plus";

//state的类型限制
interface storeType {
  categoryList1: reqCategoryListType;
  categoryList2: reqCategoryListType;
  categoryList3: reqCategoryListType;
  category1Id: number | null;
  category2Id: number | null;
  category3Id: number | null;
}

const useAttrStore = defineStore("attr", {
  //state数据(categoryId在没有值的时候默认为0，但是后来发现select中使用的时候,必须要写null,所以我们改为null)
  state: (): storeType => {
    return {
      categoryList1: [],
      categoryList2: [],
      categoryList3: [],
      category1Id: null,
      category2Id: null,
      category3Id: null,
    };
  },
  getters: {},
  actions: {
    /**@getCategoryList1 请求品牌一级列表的事件*/
    async getCategoryList1() {
      try {
        const result = await requestCategoryList1();
        this.categoryList1 = result;
      } catch (e) {
        ElMessage.error("请求一级列表失败");
      }
    },
    /**@getCategoryList2 请求品牌二级列表的事件*/
    async getCategoryList2() {
      try {
        const result = await requestCategoryList2(this.category1Id as number);
        this.categoryList2 = result;
      } catch (e) {
        ElMessage.error("请求二级列表失败");
      }
    },
    /**@getCategoryList3 请求品牌三级列表的事件*/
    async getCategoryList3() {
      try {
        const result = await requestCategoryList3(this.category2Id as number);
        this.categoryList3 = result;
      } catch (e) {
        ElMessage.error("请求三级列表失败");
      }
    },
  },
});

export default useAttrStore;
